<?php

use app\common\model\Users as UsersM;
use app\common\model\ViperUser as ViperUserM;
use app\common\model\Order as OrderM;
use app\common\model\ProductOrder as ProductOrderM;
use app\common\model\ViperCardOrder;
use app\common\model\ViperCard;
use think\Db;

// 为方便系统核心升级，二次开发中需要用到的公共函数请写在这个文件，不要去修改common.php文件

//密码加密方法
function number_rand($length = 4)
{
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

//密码加密方法
function pwd($password, $salt)
{
    $pass = md5(md5($password) . $salt);
    return $pass;
}


/**
 *  订单号
**/
function c_order_sn($type = 1)
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

        switch ($type)
        {
            //门店项目订单号
            case 1:
                if (!OrderM::where('order_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
            //门店商品订单号
            case 2:
                if (!ProductOrderM::where('order_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
            //自助结账(项目与商品组合) 订单号
            case 3:
                if (!Db::name('qt_parent_order')->where('order_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
        }

    }
    return $orderSn;
}

/**
 *  订单支付单号
 **/
function p_order_sn($type = 1)
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

        switch ($type)
        {
            //门店项目支付单号
            case 1:
                if (!OrderM::where('pay_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
            //门店商品支付单号
            case 2:
                if (!ProductOrderM::where('pay_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
            //自助结账(项目与商品组合) 订单号
            case 3:
                if (!Db::name('qt_parent_order')->where('pay_no', $orderSn)->find())
                {
                    $i++;
                }
                break;
        }

    }
    return $orderSn;
}

//生成会员卡订单号
function create_ordersn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!ViperCardOrder::where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}

//生成项目订单号
function ordersn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!OrderM::where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}



//生成卡号
function create_vaipcardrdersn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!ViperCard::where('card_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}

//生成短信订单号
function create_card_recharge()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!Db::name('qt_viper_card_recharge_log')->where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}


//生成短信订单号
function sms_ordersn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!Db::name('qt_sms_recharge_log')->where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}

/*
     * 给微信发送确认订单金额和签名正确，SUCCESS信息 -xzz0521
     */
function return_success()
{
    $return['return_code'] = 'SUCCESS';
    $return['return_msg'] = 'OK';
    $xml_post = '<xml>
                    <return_code>' . $return['return_code'] . '</return_code>
                    <return_msg>' . $return['return_msg'] . '</return_msg>
                    </xml>';
    echo $xml_post;
    exit;
}
/**
 * 将xml转为array
 * @param  string $xml xml字符串
 * @return array       转换得到的数组
 */
function xml_to_array($xml){
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $result;
}
//生成订单号
function create_rearge_ordersn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!\app\common\model\VipRechargeLog::where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}


//生成结算单据
function check_order_sn()
{
    $i = 1;
    while ($i == 1) {
//        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = intval(date('Y')) - 2011 . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!Db::name('qt_check_out')->where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}



//生成会员卡订单号
function create_ordercardsn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!OrderM::where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}
//生成审批号
function create_examinesn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $find = \think\Db::name('qt_examine')->where('examine_no', $orderSn)->find();
        if (!$find) {
            $i++;
        }
    }
    return $orderSn;
}
/**
 *  转换时间日期
 **/
function ST($time, $type = 1)
{
    if($time == null){
        return null;
    }
    switch ($type) {
        case 1:
            $time = date('Y-m-d H:i:s', $time);
            break;
        case 2:
            $time = date('Y/m/d Hi:s', $time);
            break;
        case 3:
            $time = date('Y年m月d日 H:i', $time);
            break;
        case 4:
            $time = date('Y-m-d', $time);
            break;
    }
    return $time;
}

/**
 *  转换时间日期
 **/
function color($status)
{
    switch ($status) {
        case 2:
            $color = 'rgb(98,184,120)';
            break;
        case 4:
            $color = 'rgb(128,128,128)';
            break;
        default:
            $color = 'rgb(255,255,255)';
    }
    return $color;
}



//生成订单号
function create_paysn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!OrderM::where('pay_orderno', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}



//生成门店续费订单号
function create_store_order_sn()
{
    $i = 1;
    while ($i == 1) {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (!Db::name('qt_store_order')->where('order_no', $orderSn)->find()) {
            $i++;
        }
    }
    return $orderSn;
}


//token加密    1=技师端  2=用户端
function token_rand($length = 32,$source = 1)
{
    $i = 1;
    while ($i == 1) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        switch ($source) {
            case 1:
                if (!UsersM::where('login_token', $randomString)->find()) $i++;
                break;
            case 2:
                if (!ViperUserM::where('login_token', $randomString)->find())  $i++;
                break;
        }
    }
    return $randomString;
}

//获取图片的绝对路径
function get_img_path($img_id = 0)
{
    $path = model('admin/attachment')->getFilePath($img_id);
    if ($path == '') {
        return '';
    } else {
        return config('site_url') . $path;
    }
}

//对相册 1,2,3 图片进行路径处理
function get_album_array_path($str)
{
    $data = [];
    if (!empty($str)) {
        $album = explode(',', $str);
        foreach ($album as $k => $v) {
            $data[$k]['image'] = get_img_path($v);
            $data[$k]['id'] = $v;
        }
    }
    return $data;
}

/**
 *  获取图片的绝对路径
 **/
function new_get_img_path($img_id = null,$prefix = true)
{
    $path = model('admin/attachment')->getFilePath($img_id);
    if($path)
    {
        if(preg_match('/http/',$path))
        {
            return $path;
        }else{
            if($prefix)
            {
                return getUrl().$path;
            }else{
                return $path;
            }
        }
    }else{
        return getUrl().'/static/admin/img/none.jpg';
    }

}

/**
 *  处理微信与本地头像
 **/
function checkAvatar($avatar)
{
    if(preg_match('/http/',$avatar))
    {
        return $avatar;
    }else{
        return new_get_img_path($avatar);
    }
}

/**
 *  字符串变数组
 **/
function strToArray($str,$sym = ','){
    $array = [];
    if ($str)
    {
        $array = explode($sym,$str);
    }
    return $array;
}

//处理富文本图片
function check_textarea_img($content)
{
    $str = 'src="/uploads/images/';
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    $img_url = $http_type . $_SERVER['HTTP_HOST'];
    $strs = 'src="' . $img_url . '/uploads/images/';
    $new_content = str_replace($str, $strs, $content);
    $new_content = str_replace("<img ", "<img style='max-width:100%' ", $new_content);
    $new_content = str_replace("<video", "<video style='max-width:100%' ", $new_content);
    return $new_content;
}

//生成指定长度字符串 数字字母
function random_str($length)

{
    //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
    $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
    $str = '';
    $arr_len = count($arr);
    for ($i = 0; $i < $length; $i++) {
        $rand = mt_rand(0, $arr_len - 1);
        $str .= $arr[$rand];
    }
    return $str;
}

//数据脱敏
function hidestr($string, $start = 0, $length = 0, $re = '*')
{
    if (empty($string)) return false;
    $strarr = array();
    $mb_strlen = mb_strlen($string);
    while ($mb_strlen) {//循环把字符串变为数组
        $strarr[] = mb_substr($string, 0, 1, 'utf8');
        $string = mb_substr($string, 1, $mb_strlen, 'utf8');
        $mb_strlen = mb_strlen($string);
    }
    $strlen = count($strarr);
    $begin = $start >= 0 ? $start : ($strlen - abs($start));
    $end = $last = $strlen - 1;
    if ($length > 0) {
        $end = $begin + $length - 1;
    } elseif ($length < 0) {
        $end -= abs($length);
    }
    for ($i = $begin; $i <= $end; $i++) {
        $strarr[$i] = $re;
    }
    if ($begin >= $end || $begin >= $last || $end > $last) return false;
    return implode('', $strarr);
}

//创建邀请码
function craete_invite($length = 8,$type = 1)
{
    $i = 1;
    while ($i == 1) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }

        switch ($type)
        {
            case 1:
                if (!UsersM::where('user_invite', $randomString)->find()) {
                    $i++;
                }
                break;
            case 2:
                if (!\app\common\model\ViperUser::where('ivt_code', $randomString)->find()) {
                    $i++;
                }
                break;
        }
    }
    return $randomString;
}

/**
 * @param string $url 二维码地址
 * @param $user_num 文件名
 * @param $path 保存路径
 * @return string
 */
function scerweima($url = '', $user_num, $path)
{
    require_once Env::get('app_path') . 'common/library/phpqrcode.php';
    $value = $url;         //二维码内容
    $errorCorrectionLevel = 'L';  //容错级别
    $matrixPointSize = 5;      //生成图片大小
    //生成二维码图片
    $filename = $path . $user_num . '.png';
    QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    $QR = $filename;        //已经生成的原始二维码图片文件
    $QR = imagecreatefromstring(file_get_contents($QR));
    //输出图片
    imagedestroy($QR);
    return $filename;

}

/**
 * @param $usertablename
 * @param $usertablekey
 * @param $noticid
 * @param $type
 * @return bool新增未读记录
 */
function add_read($usertablename, $usertablekey, $noticid, $type)
{
    //增加未读消息
    $user = Db::table($usertablename)->field($usertablekey)->select();
    $newsread = array();
    foreach ($user as $k => $v) {
        $newsread[] = array(
            'user_id' => $v[$usertablekey],
            'notic_id' => $noticid,
            'status' => 1,
            'type' => $type
        );
    }
    Db::name('qt_noticread')->insertAll($newsread);
    return true;
}

/*
 * HTTP发送POST
 */
function http_request($url, $data)
{
    $ch = curl_init();//创建连接
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//将数组转换为URL请求字符串，否则有些时候可能服务端接收不到参数
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //接收服务端范围的html代码而不是直接浏览器输出
    curl_setopt($ch, CURLOPT_HEADER, false);
    $res = curl_exec($ch);//接受响应
    curl_close($ch);//关闭连接
    $result = json_decode($res, true);
    return $result;
}

//发送get请求
function https_get($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'ERROR' . curl_error($curl);
    }
    curl_close($curl);
    return $data;
}

function sku_rand($length = 8, $goods_id)
{
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    $sku_code = 'SKU' . $goods_id . $randomString;
    $res = Db::name('qt_point_sku')->where('sku_code', $sku_code)->find();
    if ($res) {
        $sku_code = sku_rand(8, $goods_id);
    }
    return $sku_code;
}

/**
 *
 * 插入消息日志
 */
function message($examineNo,$userId,$toUserId,$title,$time,$content,$type,$status,$datatype = 2){
    $data['user_id'] = $userId;
    $data['examine_no'] = $examineNo;
    $data['to_user_id'] = $toUserId;
    $data['title'] = $title;
    $data['time'] = $time;
    $data['content'] = $content;
    $data['oa_type'] = $type;
    $data['status'] = $status;
    $data['type'] = $datatype;
    $data['created_time'] = time();
    \think\Db::name('qt_message')->insert($data);
}

/**
 *
 * 插入通知消息
 */
function notic($notic_id = '0',$user_id,$title,$content,$type){
    $data['notic_id'] = $notic_id;
    $data['user_id'] = $user_id;
    $data['title'] = $title;
    $data['content'] = $content;
    $data['type'] = $type;
    $data['status'] = '1';
    $data['type'] = $title;
    $data['creaetd_time'] = time();
    \think\Db::name('qt_message')->insert($data);
}


/**
 * curl请求
 */
function request_url($url, $post = array())
{
    if (empty($url)) return '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // 需要以post的方式发送的数据
    if (!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($post) ? http_build_query($post) : $post);
    }
    $p_url = parse_url($url);
    if (isset($p_url['scheme']) && $p_url['scheme'] == 'https') {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    }
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); // 自动设置Referer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回curl获取到的内容而不是直接输出
    curl_setopt($ch, CURLOPT_HEADER, false); // 不显示返回的header内容
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5秒超时

    try {
        $content = curl_exec($ch);
    } catch (\Exception $e) {

    }

    //处理BOM
    if (preg_match('/^\xEF\xBB\xBF/', $content)) {
        $content = substr($content, 3);
    }

    curl_close($ch);
    return $content;
}

/**
 *  数据打印
 **/
function p($data, $type = false)
{
    $str = '<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 14px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
    // 如果是boolean或者null直接显示文字；否则print
    if (is_bool($data)) {
        $show_data = $data ? 'true' : 'false';
    } elseif (is_null($data)) {
        $show_data = 'NULL';
    } elseif ($type == false) {
        $show_data = print_r($data, true);
    } elseif ($type == 1) {
        $show_data = dump($data);
    }
    $str .= $show_data;
    $str .= '</pre>';
    echo $str;
    exit();
}

//生成二维码
function create_ewm($url='',$path,$filename,$ewm_size = 3){
    require_once Env::get('app_path').'common/library/phpqrcode.php';
    $value = $url;         //二维码内容
    $errorCorrectionLevel = 'L';  //容错级别
    $matrixPointSize = $ewm_size; //生成图片大小
    //查询是否已经生成二维码
    if (!file_exists($path)){
        mkdir($path);
    }
    //生成二维码图片
    QRcode::png($value,$path.$filename , $errorCorrectionLevel, $matrixPointSize, 2);
    $QR = $path.$filename;        //已经生成的原始二维码图片文件
    $QR = imagecreatefromstring(file_get_contents($QR));
    //输出图片
    imagedestroy($QR);
    return $filename;
}

function getUrl()
{
    if(isset($_SERVER['REQUEST_SCHEME'])&&$_SERVER['REQUEST_SCHEME']=='https') $head = 'https';
    else $head = 'http';
    return $head."://".$_SERVER['HTTP_HOST'];
}

//生成推广海报
function collection_poster($accessToken,$user_id,$param = [],$delete = false)
{
    $filename       =   ceil($user_id / 500);
    $path           =   "uploads/agent/".$filename.'/'.$user_id.'_mini'.'.png';          //纯二维码文件存放路径
    $poster_path    =   "uploads/agent/".$filename.'/'.$user_id.'_mini__pay'.'.png';     //海报文件存放路径


    //生成二维码图片
    $num    =   ceil($user_id/500);
    $path_url   =   "uploads/agent/".$num;
    if(!file_exists($path_url)){
        mkdir($path_url);
    }

    //如果 delete = true  表示先删除之前的收款码与海报
    if($delete)
    {
        if(file_exists($path))          unlink($path);
        if(file_exists($poster_path))   unlink($poster_path);
    }

    if(!file_exists($path)){
        $scene = "yqm=".$param['ivt_code'];
        create_mini_code("uploads/agent/".$filename,$user_id.'_mini'.'.png',$scene,'pages/tab-bar/index',$accessToken);
    }

    if(!file_exists($poster_path)){
        $posterFileUrl = new_get_img_path(config('share_img'),false);          //合成图
//        $posterFileUrl = "uploads/poster/skm.png";          //合成图
        //生成海报
        watermark($posterFileUrl,$path,$param,"uploads/agent/".$filename.'/'.$user_id.'_mini__pay');

    }

    return [$path,$poster_path];
}

/**
 * 生成小程序二维码
 * @param  string $qr_path 		存储路径,相对于程序根目录(例如:/Public/Qrcode/)
 * @param  string $filename 	存储的图片名称(例如:aaa.png)
 * @param  string $scene 		二维码场景值
 * @param  string $page 		二维码跳转页面
 * @param  string $expires_in 	二维码有效时间
 * @return [type]         [description]
 */
function create_mini_code($qr_path,$filename,$scene,$page='',$accessToken)
{
    if(empty($qr_path)) return false;
    if(empty($filename)) return false;
    if(empty($scene)) return false;

    $file = $qr_path.'/'.$filename;
    $savePath = $file;
    $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
    $qrcode = array(
        'scene'			=> $scene,
        'width'			=> 200,
        'page'			=> $page,
        'auto_color'	=> false
    );
    $result = request_url($url,json_encode($qrcode));
    $errcode = json_decode($result,true)['errcode'];
    if($errcode) return false;
    file_put_contents($savePath,$result);			//	将获取到的二维码图片流保存成图片文件
}

/**
 *  合成图片
 **/
function watermark($image,$waterImage,$param = [],$filename)
{
    $dst = imagecreatefromstring(file_get_contents(WebPath.$image));
    $src = imagecreatefromstring(file_get_contents(WebPath.$waterImage));
    $avatar = imagecreatefromstring(file_get_contents(checkAvatar($param['avatar'])));

    list($src_w, $src_h) = getimagesize(WebPath.$waterImage);
    list($dst_xp, $dst_yp) = getimagesize(WebPath.$image);

    //用户头像
    list($avatar_w, $avatar_h) = getimagesize(checkAvatar($param['avatar']));


    $dst_x = ($dst_xp - $src_w) / 2;
    $dst_y = ($dst_yp - $src_h) / 2;
    $dst_y = $dst_y + 150;

    $dst_font_y = $dst_y + $src_h + 80;

    $avatar_x  = ($dst_xp - $avatar_w) / 2;

    //合并图片
    imagecopymerge($dst, $src, $dst_x, $dst_y, 0, 0, $src_w, $src_h, 100);

    imagecopymerge($dst, $avatar, $avatar_x, $dst_y - 350, 0, 0, 132, 132, 100);

    $background = imagecreatetruecolor($dst_xp,$dst_yp);
//    p(WebPath);
    $font_path =  WebPath.'uploads/font/simhei.ttf';   //字体绝对路径

    //分享说明文字
    $type_space = imagettfbbox(22, 0, $font_path, $param['show']);
    $image_width  = abs($type_space[4] - $type_space[0]) + 10;
    $dst_font_x = ($dst_xp - $image_width ) / 2;
    //合并文字
    imagefttext($dst, 22, 0, $dst_font_x, $dst_font_y, imagecolorallocate($background, 153, 153, 153), $font_path, $param['show']);

    //邀请码文字
    $code_space = imagettfbbox(42, 0, $font_path, '邀请码:'.$param['ivt_code']);
    $code_image_width  = abs($code_space[4] - $code_space[0]) + 10;
    $dst_code_font_x = ($dst_xp - $code_image_width ) / 2;
    imagefttext($dst, 42, 0, $dst_code_font_x, $dst_y - 50, imagecolorallocate($background, 51, 51, 51), $font_path, '邀请码:'.$param['ivt_code']);


    //昵称
    $name_space = imagettfbbox(30, 0, $font_path, $param['nickname']);
    $name_image_width  = abs($name_space[4] - $name_space[0]) + 10;
    $dst_name_font_x = ($dst_xp - $name_image_width ) / 2;
    imagefttext($dst, 30, 0, $dst_name_font_x, $dst_y - 150, imagecolorallocate($background, 51, 51, 51), $font_path, $param['nickname']);

    list($dst_w, $dst_h, $dst_type) = getimagesize(WebPath.$waterImage);
    switch ($dst_type) {
        case 1:
            header('Content-Type: image/gif');
            imagegif($dst);
            break;
        case 2:
            header('Content-Type: image/jpeg');
            imagejpeg($dst);
            break;
        case 3:
            header('Content-Type: image/png');
            imagepng($dst);
            break;
        default:
            break;
    }
    // 是否存在
    if(!file_exists($filename.'.png')){
        imagepng($dst,$filename.'.png');
    }
    imagedestroy($dst);
    imagedestroy($src);
    ob_end_clean();
}

function string2bytes($str){
    $bytes=array();
    for ($i=0; $i < strlen($str); $i++) {
        $tmp=substr($str, $i,1);
        $bytes[]=bin2hex($tmp);
    }
    $data = implode('',$bytes);
    return '02'.$data.'03';
}

function  ToStr ($bytes)
{
    $str="";
    for   ($i=0;$i<count($bytes);$i++)
        $str.=sprintf("%02X",$bytes[$i]);

    return   $str;
}


/**
 * 二维数组去重
 * @param $array
 * @param $unique_key
 * @return array
 */
function unique_2d_array_by_key($array, $unique_key)
{
    $tmp_key[] = array();
    foreach ($array as $key => &$item) {
        if (is_array($item) && isset($item[$unique_key])) {
            if (in_array($item[$unique_key], $tmp_key)) {
                unset($array[$key]);
            } else {
                $tmp_key[] = $item[$unique_key];
            }
        }
    }
    //重置一下二维数组的索引
    return array_slice($array, 0, count($array), false);
}


/**
 * 插入支付信息所有
 * @param $payContent [支付信息json传值过来]
 * @param $checkOutId [结账单ID]
 * @param $userInfo [结账人信息]
 * @param $type [结账类型 1 充值 2 消费 3 开卡]
 * @param $cardMoney [会员支付金额]
 */
function check_out_pay_all($payContent,$checkOutId,$userInfo,$type,$isVip = 0,$charge_recovery = 0,$viper_card_id = 0){
    $payContent = json_decode($payContent,true);
    $insertData = [];
    foreach ($payContent as $key=>$value){
        if($value['pay_id'] != '6'){
            $payName = Db::name('qt_pay_type')->where(['id'=>$value['pay_id']])->value('name');
            if($charge_recovery == '1'){
                $charge_recovery = $value['pay_money'];
            }
            $insertData[$key] = [
                'store_id'=>$userInfo['store_id'],
                'user_id'=>$userInfo['id'],
                'check_out_id'=>$checkOutId,
                'pay_id'=>$value['pay_id'],
                'pay_name'=>$payName,
                'pay_money'=>$value['pay_money'],
                'type'=>$type,
                'time'=>date('Y-m-d'),
                'is_vip'=>$isVip,
                'create_time'=>time(),
                'charge_recovery'=>$charge_recovery,
                'viper_card_id'=>$viper_card_id,
            ];
            if($viper_card_id != 0){
                $viperCardData = Db::name('qt_viper_card')->field('amount,give_amount')->where(['id'=>$viper_card_id])->find();
                $insertData[$key]['card_amount'] = $viperCardData['amount'];
                $insertData[$key]['card_give_amount'] = $viperCardData['give_amount'];
            }
        }
    }
    Db::name('qt_check_out_pay')->insertAll($insertData);
}

/**
 * 会员卡支付方式
 * @param $viperCardId
 * @param $payContent
 * @param $checkOutId
 * @param $userInfo
 * @param $type
 * @param int $cardMoney
 * @param int $cardGaveMoney
 * @param int $card_amount
 * @param int $card_give_amount
 */
function check_out_card_pay_all($viperCardId,$payMoney,$checkOutId,$userInfo,$type,$cardMoney = 0,$cardGaveMoney = 0,$card_amount = 0,$card_give_amount = 0,$charge_recovery = 0){
    if($charge_recovery == '1'){
        $charge_recovery = $payMoney;
    }
    $insertData = [
            'store_id'=>$userInfo['store_id'],
            'user_id'=>$userInfo['id'],
            'check_out_id'=>$checkOutId,
            'pay_id'=>'6',
            'pay_name'=>'会员卡',
            'pay_money'=>$payMoney,
            'card_money'=>$cardMoney,
            'card_give_money'=>$cardGaveMoney,
            'card_amount'=>$card_amount,
            'card_give_amount'=>$card_give_amount,
            'type'=>$type,
            'time'=>date('Y-m-d'),
            'create_time'=>time(),
            'viper_card_id'=>$viperCardId,
            'charge_recovery'=>$charge_recovery,
        ];
        Db::name('qt_check_out_pay')->insert($insertData);

}







/**
 * 插入支付信息单个
 * @param $payContent [支付信息json传值过来]
 * @param $checkOutId [结账单ID]
 * @param $userInfo [结账人信息]
 * @param $type [结账类型 1 充值 2 消费 3 开卡]
 * @param $cardMoney [会员支付金额]
 */
function check_out_pay_single($payContent,$checkOutId,$userInfo,$type,$cardMoney = 0){
    $insertData = [
        'store_id'=>$userInfo['store_id'],
        'user_id'=>$userInfo['id'],
        'check_out_id'=>$checkOutId,
        'pay_id'=>$payContent['pay_id'],
        'pay_name'=>$payContent['pay_name'],
        'pay_money'=>$payContent['pay_money'],
        'card_money'=>$cardMoney,
        'type'=>$type,
        'time'=>date('Y-m-d'),
        'create_time'=>time(),
    ];
    Db::name('qt_check_out_pay')->insertAll($insertData);
}

/**
 * 获取门店排钟规则
 * @param $storeID
 * @param string $type
 * @return array
 */
function storeQueue($storeID,$type = '1'){
    $queue = Db::name('qt_queue_rule')->where(['store_id'=>$storeID,'type'=>$type])->find();
    return $queue;
}


/**
 * 置头牌
 * @param $storeID
 * @param $userId
 */
function topSort($storeID,$userId){
    $list = Db::name('qt_order_queue')->field('id,sort')
        ->where('sort', 'neq', '0')
        ->where('store_id', $storeID)
        ->order('sort asc')
        ->select();
    //获取老用户的坐标位置
    $oldSort = Db::name('qt_order_queue')->where('user_id', $userId)->value('sort');
    $oldNumber = Db::name('qt_order_queue')
        ->where(['store_id'=>$storeID])
        ->where('sort', '<', $oldSort)
        ->count();
    //头牌
    $newNumber = '0';
    $oldSort = $oldNumber;
    $newSort = $newNumber;
    //id 主键 sort 排序值
    //id集合
    $idArr = [];
    //排序集合
    $sortArr = [];
    foreach ($list as $item) {
        $idArr[] = $item['id'];
        $sortArr[] = $item['sort'];
    }
    //记录要拖动的id
    $oldValue = $idArr[$oldSort];
    //删除这个要拖动的id
    unset($idArr[$oldSort]);
    //插入新的位置，并自动移位
    array_splice($idArr, $newSort, 0, $oldValue);
    //重新设置排序
    $set = [];
    for ($i = 0; $i < count($idArr); $i++) {
        $set[$i]['id'] = $idArr[$i];
        $set[$i]['sort'] = $sortArr[$i];
    }
    foreach ($set as $key => $value) {
        Db::name('qt_order_queue')->where('id', $value['id'])->update(['sort' => $value['sort']]);
    }
}


function goodsOrderMessage($storeId,$goodsData,$roomId){
    $users = Db::name('qt_users')->where(['store_id'=>$storeId,'group'=>'2','status'=>0])->column('id');
    $storeName = Db::name('qt_store')->where(['id'=>$storeId])->value('name');
    $roomData = Db::name('qt_room')->where(['id'=>$roomId])->find();
    $content = "{".$storeName."}房间：".$roomData['name'].",商品:";
    foreach ($goodsData as $key=>$value){
        $content.= $value['product_name'].',数量:'.$value['num'].',';
    }
    foreach ($users as $key=>$value){
        $insert[$key] = [
            'to_user_id'=>$value,
            'title'=>$roomData['name'],
            'room_id'=>$roomId,
            'content'=>$content,
            'status'=>'1',
            'type'=>'3',
            'created_time'=>time(),
        ];
    }
    Db::name('qt_message')->insertAll($insert);
}







